package cn.tac.test.servlet.cheapter1;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author : tac
 * @since : 09/09/2017
 */
public class HttpServer {
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // shutdown command
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private boolean shoutdown = false;

    public static void main(String[] args) {
        HttpServer httpServer = new HttpServer();
        httpServer.await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        System.out.println("服务已启动");
        System.out.println("webroot: " + WEB_ROOT);
        System.out.println();

        while (!shoutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();
                Request request = new Request(input);
                request.parse();
                if(request.isSuccess()){
                    System.out.println(request);
                    Response response = new Response(output);
                    response.setRequest(request);
                    response.sendStaticResource();
                    String uri = request.getURI();
                    System.out.println(uri);
                    shoutdown = uri.equals(SHUTDOWN_COMMAND);
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
